package email

import (
	"gopkg.in/gomail.v2"
)

type Emailer interface {
	Send(subject string, message string) error
}

func NewEmail(host string, port int, from string, password string, to string) Emailer {
	email := email{}
	email.setSmtp(host, port, from, password, to)
	return &email
}

type email struct {
	host     string
	port     int
	from     string
	password string
	to       string
}

func (e *email) setSmtp(host string, port int, from string, password string, to string) {
	e.host = host
	e.port = port
	e.password = password
	e.from = from
	e.to = to
}

func (e *email) Send(subject string, message string) error {
	m := gomail.NewMessage()
	//发送人
	m.SetHeader("From", e.from)
	//接收人
	m.SetHeader("To", e.to)

	m.SetHeader("Subject", subject)
	//内容
	m.SetBody("text/html", message)

	dial := gomail.NewDialer(e.host, e.port, e.from, e.password)

	// 发送邮件
	if err := dial.DialAndSend(m); err != nil {
		return err
	}

	return nil
}
